<template>
  <div class="modal-overlay" @click="handleOverlayClick">
    <div class="modal-content modal-main" @click.stop>
      <div class="modal-header">
        <h3>数据导出</h3>
        <button class="close-btn" @click="handleClose">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>

      <div class="modal-body">
        <!-- 文件选择 -->
        <div class="form-group">
          <label class="form-label"
            >选择文件 <span class="required">*</span></label
          >
          <div class="file-selector">
            <div class="file-list">
              <div
                v-for="file in availableFiles"
                :key="file.name"
                class="file-item"
                :class="{ selected: selectedFileNames.includes(file.name) }"
                @click="toggleFileSelection(file.name)"
              >
                <div class="file-checkbox">
                  <svg
                    v-if="selectedFileNames.includes(file.name)"
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  >
                    <polyline points="20,6 9,17 4,12"></polyline>
                  </svg>
                </div>
                <div class="file-info">
                  <div class="file-name">{{ file.name }}</div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="fileError" class="error-message">{{ fileError }}</div>
        </div>

        <!-- 时间范围选择 -->
        <div class="form-group">
          <label class="form-label"
            >时间范围 <span class="required">*</span></label
          >
          <div class="time-range" v-if="flag === 'RJ'">
            <div class="time-input">
              <label>开始时间</label>
              <!-- <input
                type="datetime-local"
                v-model="startTime"
                :max="endTime"
                class="form-input"
                @input="validateTimeRange"
              /> -->
              <div class="datetime-input-group">
                <input
                  v-model="start_date"
                  type="date"
                  class="form-input datetime-date-input"
                  :placeholder="'选择开始日期'"
                />
                <TimeSelector
                  v-model="start_time"
                  input-class="datetime-time-input"
                  placeholder="选择开始时间"
                />
              </div>
            </div>
            <div class="time-input">
              <label>结束时间</label>
              <!-- <input
                type="datetime-local"
                v-model="endTime"
                :min="startTime"
                class="form-input"
                @input="validateTimeRange"
              /> -->
              <div class="datetime-input-group">
                <input
                  v-model="end_date"
                  type="date"
                  class="form-input datetime-date-input"
                  :placeholder="'选择结束日期'"
                />
                <TimeSelector
                  v-model="end_time"
                  input-class="datetime-time-input"
                  placeholder="选择结束时间"
                />
              </div>
            </div>
          </div>
          <div class="time-range" v-else>
            <div class="time-input">
              <label>开始时间</label>
              <input
                v-model="startTime"
                :min="0"
                :max="endTime"
                class="form-input"
                @input="validateTimeRange"
                placeholder="请输入开始时间"
              />
              <!-- 开始时间错误提示 -->
              <p v-if="startTimeError" class="error-message">
                {{ startTimeError }}  <!-- 显示错误信息 -->
              </p>
            </div>
            <div class="time-input">
              <label>结束时间</label>
              <input
                v-model="endTime"
                :min="0"
                class="form-input"
                @input="validateTimeRange"
                placeholder="请输入结束时间"
              />
              <!-- 结束时间错误提示 -->
              <p v-if="endTimeError" class="error-message">
                {{ endTimeError }}  <!-- 显示错误信息 -->
              </p>
            </div>
          </div>
        </div>

        <!-- 参数选择 -->
        <div class="form-group">
          <label class="form-label"
            >选择参数 <span class="required">*</span></label
          >
          <div class="shuttle-container">
            <shuttleBox
              :parameters="props.parameters"
              v-model:selectedParams="selectedParams"
            />
          </div>
          <div v-if="paramsError" class="error-message">{{ paramsError }}</div>
        </div>

        <div class="control-group">
          <label>模拟量小数位数：</label>
          <input
            v-model="precLength"
            @change="chacngePrec"
            type="number"
            class="form-input"
            :placeholder="'请输入小数位数'"
            min="0"
            max="6"
            style="width: 18%"
          />
          <p v-if="precLengthError" class="error-message">
            {{ precLengthError }}  <!-- 显示错误信息 -->
          </p>
        </div>


      </div>

      <div class="modal-footer">
        <button class="tech-btn-warn import-btn-cancel" @click="handleClose">取消</button>
        <button
          class="tech-btn import-btn-primary"
          @click="handleExport"
          :disabled="!isFormValid"
        >
          导出
        </button>
      </div>
    </div>
    <!-- 消息提示组件 -->
    <Message ref="messageRef" />
    <!-- 全局loading遮罩层 -->
    <div v-if="loading" class="loading-overlay">
      <div class="spinner"></div>
      <div class="loading-text">{{ loadingText }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from "vue";
import WithAPI from "../parameter/parameter.api.ts";
import ExportDataAPI from "./exportData.api.ts";
import shuttleBox from "./shuttleBox.vue";
import TimeSelector from "../plugin/TimeSelector.vue";
import Message from "@/components/BaseComponents/Message.vue";
import { useFileSelectionStore } from "@/stores/fileSelection";
const fileSelectionStore = useFileSelectionStore();

// 选中状态
const selectedFileA = ref(fileSelectionStore.selectedFileA);
const selectedFileB = ref(fileSelectionStore.selectedFileB);
const selectedFileC = ref(fileSelectionStore.selectedFileC);
const selectedFileD = ref(fileSelectionStore.selectedFileD);

// 选中的文件列表 是selectedFileA、selectedFileB、selectedFileC、selectedFileD的并集
const selectedFiles = ref<string[]>([]);
interface ParamInfo {
  name: string;
  description?: string;
}

interface Props {
  visible: boolean;
  parameters: ParamInfo[];
}

interface Emits {
  (e: "close"): void;
}

// 消息提示组件引用
const messageRef = ref<InstanceType<typeof Message> | null>(null);
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const flag = localStorage.getItem("flag");
// 响应式数据
const selectedFileNames = ref<string[]>([]);
const availableFiles = ref<Array<{ name: string }>>([]);
const startTime = ref("");
const endTime = ref("");
const start_date = ref()
const start_time = ref()
const end_date = ref()
const end_time = ref()
const selectedParams = ref<string[]>([]);
const searchKeyword = ref("");

//模拟量小数位数
const precLength = ref(3)
const chacngePrec = () =>{
  // 为空提醒
  if (precLength.value === '' || precLength.value === null || precLength.value === undefined){
    precLengthError.value = '请输入0-6之间的正整数'
    return;
  }
  // 小数提醒
  if (!/^\+?\d+$/.test(precLength.value)){
    precLengthError.value = '请输入0-6之间的正整数'
    return;
  }
  precLengthError.value = '';
  if (precLength.value > 6){
    precLength.value = 6;
  }else if (precLength.value < 0){
    precLength.value = 0;
  }
}

// 错误信息
const fileError = ref("");
const startTimeError = ref("");
const endTimeError = ref("");
const paramsError = ref("");
const precLengthError = ref("");

// 全局loading
const loading = ref(false);
const loadingText = ref("正在导出，请稍候...");

const isFormValid = computed(() => {
  let isStartTimeValid, isEndTimeValid;
  if (flag === 'RJ') {
    isStartTimeValid = !!start_date.value && !!start_time.value;
    isEndTimeValid = !!end_date.value && !!end_time.value;
  } else {
    isStartTimeValid = startTime.value !== '' && startTime.value !== null && startTime.value !== undefined;
    isEndTimeValid = endTime.value !== '' && endTime.value !== null && endTime.value !== undefined;
  }
  return (
    selectedFileNames.value.length > 0 &&
    isStartTimeValid &&
    isEndTimeValid &&
    selectedParams.value.length > 1 &&
    !startTimeError.value &&
    !endTimeError.value &&
    !fileError.value &&
    !paramsError.value &&
    !precLengthError.value
  );
});

// 方法
const toggleFileSelection = (fileName: string) => {
  const index = selectedFileNames.value.indexOf(fileName);
  if (index > -1) {
    selectedFileNames.value.splice(index, 1);
  } else {
    selectedFileNames.value.push(fileName);
  }
  fileError.value = "";
};

const validateTimeRange = () => {
  startTimeError.value = '';
  endTimeError.value = '';
  console.log(startTime.value)
  if (flag === 'RJ') {
    // RJ模式下，四个字段都必填
    if (!start_date.value || !start_time.value) {
      startTimeError.value = '请选择开始日期和时间';
    }
    if (!end_date.value || !end_time.value) {
      endTimeError.value = '请选择结束日期和时间';
    }
    if (!startTimeError.value && !endTimeError.value) {
      // 拼接成完整时间字符串
      const startStr = `${start_date.value} ${start_time.value}`;
      const endStr = `${end_date.value} ${end_time.value}`;
      const start = new Date(startStr.replace(/-/g, '/'));
      const end = new Date(endStr.replace(/-/g, '/'));
      if (isNaN(start.getTime())) {
        startTimeError.value = '开始时间格式不正确';
      }
      if (isNaN(end.getTime())) {
        endTimeError.value = '结束时间格式不正确';
      }

    }
  } else {
    // 非RJ模式，原有数字校验
    if (startTime.value === '' || startTime.value === null || startTime.value === undefined) {

      startTimeError.value = '请输入开始时间';
    }else if (!/^\+?\d+$/.test(startTime.value)){
      startTimeError.value = '格式不正确';
    }
    if (endTime.value === '' || endTime.value === null || endTime.value === undefined) {
      endTimeError.value = '请输入结束时间';
    }else if(!/^\d+$/.test(endTime.value)){
      endTimeError.value = '格式不正确';
    }
    if (startTimeError.value || endTimeError.value) {
      return;
    }
  }
};

const handleOverlayClick = () => {
  handleClose();
};

const handleClose = () => {
  emit("close");
};

const handleExport = async () => {
  // 最终验证

  if (selectedFileNames.value.length === 0) {
    fileError.value = '请选择要导出的文件';
    return;
  }


  if (selectedParams.value.length === 1) {
    paramsError.value = '请至少选择一个参数';
    return;
  }

  let start, end;
  if (flag === 'RJ') {
    const startStr = `${start_date.value} ${start_time.value}`;
    const endStr = `${end_date.value} ${end_time.value}`;
    start = new Date(startStr.replace(/-/g, '/'));
    end = new Date(endStr.replace(/-/g, '/'));
  } else {
    start = Number(startTime.value);
    end = Number(endTime.value);
  }

  if (flag === 'RJ' && (!start || !end || (start instanceof Date && isNaN(start.getTime())) || (end instanceof Date && isNaN(end.getTime())) || (start instanceof Date && end instanceof Date && start >= end))) {
    messageRef.value?.show({
      type: "error",
      content: "结束时间必须大于开始时间",
      duration: 5000,
    });
    return;
  }
  if (flag !== 'RJ' && start >= end) {
    messageRef.value?.show({
      type: "error",
      content: "结束时间必须大于开始时间",
      duration: 5000,
    });
    return;
  }

  if (!isFormValid.value) {
    return;
  }
  const selectedParamsNames: any[] = [];
  selectedParams.value.forEach((param) => {
    selectedParamsNames.push(param.label);
  });

  const params = {
    startTime: flag === 'RJ' ? `${start_date.value} ${start_time.value}` : startTime.value,
    endTime: flag === 'RJ' ? `${end_date.value} ${end_time.value}` : endTime.value,
    fileNames: selectedFileNames.value,
    paramNames: selectedParamsNames,
    precLength: (precLength.value || precLength.value === 0) ? precLength.value : 3
  };
  console.log(params);
  loading.value = true;
  try {
    // 调用导出接口
    const res = await ExportDataAPI.exportFile(params);
    // 假设后端返回的是文件流
    if (res && res.data) {
      // 获取文件名
      let fileName = '数据导出.csv';
      const disposition = res.headers && (res.headers['content-disposition'] || res.headers['Content-Disposition']);
      if (disposition) {
        const match = disposition.match(/filename="?([^"]+)"?/);
        if (match && match[1]) {
          fileName = decodeURIComponent(match[1]);
        }
      }
      // 创建blob并下载
      const blob = new Blob([res.data]);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);

      messageRef.value?.show({
        type: 'success',
        content: '导出成功',
        duration: 3000,
      });
      nextTick(() => {
        handleClose();
      });
    } else {
      messageRef.value?.show({
        type: 'error',
        content: '导出失败',
        duration: 5000,
      });
      return;
    }
  } catch (error) {
    messageRef.value?.show({
      type: 'error',
      content: error?.message || '导出失败',
      duration: 5000,
    });
    return;
  } finally {
    loading.value = false;
  }
};

// 监听器
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      // 重置表单
      selectedFileNames.value = [];
      startTime.value = "";
      endTime.value = "";
      selectedParams.value = [...props.parameters.map((param) => param.name)]; // 默认全选
      searchKeyword.value = "";
      fileError.value = "";
      startTimeError.value = "";
      endTimeError.value = "";
      paramsError.value = "";
    }
  }
);

// 组件挂载时设置默认值
onMounted(() => {
  if (props.visible) {
    selectedParams.value = [...props.parameters.map((param) => param.name)];
    // WithAPI.getFileWithCleaned().then((res: { data: string[] }) => {
    //   if (res && res.data) {
    //     let rules: Array<{ name: string }> = [];
    //     res.data.forEach((item: string) => {
    //       rules.push({
    //         name: item,
    //       })
    //     });
    //     availableFiles.value = rules;
    //   }
    // })
    // selectedFileA、selectedFileB、selectedFileC、selectedFileD 可能为字符串或数组，需统一处理为数组
    function toArray(val: any) {
      if (Array.isArray(val)) {
        return val;
      }
      if (typeof val === "string" && val) {
        return [val];
      }
      return [];
    }
    selectedFiles.value = [
      ...toArray(selectedFileA.value),
      ...toArray(selectedFileB.value),
      ...toArray(selectedFileC.value),
      ...toArray(selectedFileD.value),
    ];

    // 去重
    selectedFiles.value = [...new Set(selectedFiles.value)];
    availableFiles.value = selectedFiles.value.map((file) => ({ name: file }));
  }
});
</script>

<style scoped>
@import '../../../src/assets/css/theme.css';
@import '../../../src/assets/css/buttons.css';
@import '../../../src/assets/css/modal.css';
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 900px;
  max-height: 90vh;
  overflow-y: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
    color: var(--text-color);
    font-size: 20px;
    font-weight: 700;
  transition: color 0.2s;
}

.close-btn:hover {
    color: rgba(0, 0, 0, 0.85);
}
.import-btn-cancel, .import-btn-primary{
  height: 36px;
  font-size: 0.875rem;
  padding: 0.35rem 0.75rem;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: all 0.2s ease;
}
.modal-body {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.required {
  color: var(--error-color);
}

.file-selector {
  border: 1px solid #d1d5db;
  border-radius: 6px;
  overflow: hidden;
}

.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-count {
  font-size: 14px;
  color: #6b7280;
}

.file-list {
  max-height: 200px;
  overflow-y: auto;
}

.file-item {
  font-size: 14px;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid var(--table-solid);
  transition: background-color 0.2s;
    background: var(--btn-color);
}

.file-item:last-child {
  border-bottom: none;
}

.file-item:hover {
  background-color: var(--btn-hover-color);
}

.file-item.selected {
  background-color: var(--btn-click-color);
  border-color: var(--table-solid);
}

.file-checkbox {
  width: 18px;
  height: 18px;
  border: 1px solid var(--btn-click-color);
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--global-color-white);
  background-color: var(--ant-checkbox-checked);
}

.file-item:not(.selected) .file-checkbox {
    border: 1px solid var(--btn-color);
    background-color: var(--ant-checkbox-inner);
    color: var(--global-color-white);
}

.file-info {
  flex: 1;
}

.file-name {
  color: var(--text-color);
}

.time-range {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.time-input {
  display: flex;
  flex-direction: column;
}

.time-input label {
  margin-bottom: 6px;
  font-size: 14px;
}

/* DateTime Input Group Styles */
.datetime-input-group {
  display: flex;
  gap: 8px;
  width: 100%;
}

.datetime-date-input {
  flex: 1;
  min-width: 220px;
}

.datetime-time-input {
  flex: 1;
  min-width: 100px;
}

.form-input {
  padding: 8px 12px;
  background: var(--select-background);
  color: var(--text-color);
  border: 1px solid var(--input-border-color);
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.error-message {
  color: var(--error-color);
  font-size: 12px;
  margin-top: 4px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 12px 12px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--loading-bg-color);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.spinner {
  border: 8px solid #f3f3f3;
  border-top: 8px solid #3498db;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.loading-text {
  color: var(--text-color);
  font-size: 14px;
  font-weight: bold;
  margin-top: 10px;
}

</style>
